package com.jn.gsondemo;

import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;

import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BookDetailActivity extends AppCompatActivity {
    private TextView bookTitleView;
    private TextView bookAuthorView;
    private TextView bookDescriptionView;
    private ImageView bookImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_detail);

        bookTitleView = findViewById(R.id.book_title);
        bookAuthorView = findViewById(R.id.book_author);
        bookDescriptionView = findViewById(R.id.book_description);
        bookImageView = findViewById(R.id.book_image);

        loadBookDetails();
    }

    private void loadBookDetails() {
        try {
            InputStream inputStream = getResources().openRawResource(R.raw.book);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            reader.close();
            String json = stringBuilder.toString();
            JSONObject obj = new JSONObject(json);

            bookTitleView.setText(obj.getString("title"));
            bookAuthorView.setText(obj.getString("author"));
            bookDescriptionView.setText(obj.getString("description"));

            // 使用Glide加载图片
            Glide.with(this)
                    .load(obj.getString("coverImageUrl"))
                    .error(R.drawable.ic_launcher) // 这里使用一个占位图资源
                    .into(bookImageView);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}